package com.xysoft.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.xysoft.admin.common.ElementConst;
import com.xysoft.admin.common.PageModel;
import com.xysoft.admin.common.SessionInfo;
import com.xysoft.admin.dto.ActionDTO;
import com.xysoft.admin.dto.RoleDTO;
import com.xysoft.admin.service.IRoleService;
import com.xysoft.model.Action;
import com.xysoft.model.Organization;
import com.xysoft.model.Role;
import com.xysoft.model.RoleAction;
import com.xysoft.util.JsonUtil;
import com.xysoft.util.RequestUtil;

@Component
@SuppressWarnings("unchecked")
public class RoleServiceImpl extends BaseServiceImpl implements IRoleService {
	
	@Transactional
	public String get(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int page = Integer.valueOf(RequestUtil.getValue(request, "page"));
		int limit = Integer.valueOf(RequestUtil.getValue(request, "limit"));
		Organization organ = (Organization)this.getBaseDao().get(Organization.class, sessionInfo.getOrgId());
		String hql = "from Role r where r.deleted = 0 and r.front = 1 and r.organization.id = ?";
		List<Object> values = new ArrayList<Object>();
		values.add(sessionInfo.getOrgId());
//		String name = RequestUtil.getValue(request, "name").trim();
//		if(!"".equals(name)) {
//			hql = hql + " and r.name like ?";
//			values.add("%" + name + "%");
//		}
		hql = hql + " order by r.id desc";
		List<Role> roles = this.getBaseDao().find(hql, page, limit, values);
		List<RoleDTO> dtos = new ArrayList<RoleDTO>();
		long count = 1;
		if (roles.size() > 0) {
			for (Role role : roles) {
				RoleDTO dto = new RoleDTO();
				BeanUtils.copyProperties(role, dto);
				dto.setOrgan(organ.getName());
				dtos.add(dto);
			}
		} else {
			Role roleTemp = new Role();
			roleTemp.setDeleted(false);
			roleTemp.setFront(true);
			roleTemp.setName(ElementConst.ROLENAME);
			roleTemp.setRemark(ElementConst.ROLEREMARK);
			roleTemp.setOrganization(organ);
			this.getBaseDao().save(roleTemp);
			RoleDTO dto = new RoleDTO();
			dto.setId(roleTemp.getId());
			dto.setName(ElementConst.ROLENAME);
			dto.setRemark(ElementConst.ROLEREMARK);
			dto.setOrgan(organ.getName());
			dtos.add(dto);
		}
		PageModel pm = new PageModel();
		pm.setTotal(count);
		pm.setDatas(dtos);
		return JsonUtil.toStringFromObject(pm);
	}

	@Transactional
	public String getAllAction() {
		List<Action> actions = this.getBaseDao().find("from Action a where a.front = 1 and a.leaf = 1");
		List<ActionDTO> dtos = new ArrayList<ActionDTO>();
		for (Action action : actions) {
			ActionDTO dto = new ActionDTO();
			dto.setId(action.getId());
			dto.setName(action.getKeyName());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public Map<String, Object> getAuto(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int id = Integer.valueOf(RequestUtil.getValue(request, "id"));
		Role role = (Role)this.getBaseDao().get(Role.class, id);
		if (!role.isFront() || !role.getOrganization().getKeyChar().equals(sessionInfo.getKeyChar())) return null;
		Set<RoleAction> ras = role.getRoleActions();
		String res = "";
		for (RoleAction ra : ras) {
			res = res + ra.getAction().getId() + ";";
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("success", true);
		modelMap.put("msg", res);
		return modelMap;
	}
	
	@Transactional
	public Map<String, Object> save(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int id = Integer.valueOf(RequestUtil.getValue(request, "id"));
		Role role = (Role)this.getBaseDao().get(Role.class, id);
		if (!role.isFront() || !role.getOrganization().getKeyChar().equals(sessionInfo.getKeyChar())) return null;
		Set<RoleAction> ras = role.getRoleActions();
		Map<Integer, RoleAction> rasMaps = new HashMap<Integer, RoleAction>();
		for (RoleAction ra : ras) {
			rasMaps.put(ra.getAction().getId(), ra);
		}
		String autostr = RequestUtil.getValue(request, "autostr");
		if (!"".equals(autostr)) {
			List<Action> actions = this.getBaseDao().find("from Action a where a.front = 1 and a.leaf = 1");
			Map<Integer, Action> actMaps = new HashMap<Integer, Action>();
			for (Action action : actions) {
				actMaps.put(action.getId(), action);
			}
			String[] ids = autostr.split(";");
			for (String idstr : ids) {
				int idInt = Integer.valueOf(idstr);
				if (actMaps.containsKey(idInt)) {
					if (rasMaps.containsKey(idInt)) {
						rasMaps.remove(idInt);
					} else {
						RoleAction ra = new RoleAction();
						ra.setAction(actMaps.get(idInt));
						ra.setRole(role);
						this.getBaseDao().save(ra);
					}
				}
			}
		}
		role.setRoleActions(null);
		for (RoleAction ra : rasMaps.values()) {
			this.getBaseDao().delete(ra);
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("success", true);
		modelMap.put("msg", "保存成功！");
		return modelMap;
	}
	
}
